<?php
namespace Admin\Controller;

use Common\Lib\User\UserHelper;
use Common\Lib\User\UserInfoException;
use Think\Controller;

/**
 * Class PublicController
 * @package Admin\Controller
 */
class PublicController extends Controller  {
    /**
     * 用户注册
     */
    public function register(){
        if(session('USER_ID')){
            redirect(U("Admin/Index/index"));exit();
        }
        if(IS_POST){
            $data = $_POST;
            try{
                $result = UserHelper::add($data);
                if($result){
                    $user = M('User')->find($result);
                    $this->storeLogin($user);
                    $this->success('注册成功');
                }else{
                    $this->error('注册失败');
                }
            } catch (UserInfoException $exception){
                $this->error($exception->getMessage());
            }
            //$this->error('错误');
        }else{
            $this->display();
        }
    }

    /**
     * 存储登录信息
     * @param $user
     */
    private function storeLogin($user){
        session('USER',$user);
        session('USER_ID',$user['ID']);
        session('LOGIN_TIME',date('Y-m-d H:i:s'));
    }

    /**
     * 退出登录
     */
    public function logout(){
        session_destroy();
        if(IS_AJAX){
            $this->error("请登录！",U("Admin/Public/login"));
        }else{
            redirect(U("Admin/Public/login"));
            exit();
        }
    }

    /**
     * 用户登录
     */
    public function login(){
        if(session('USER_ID')){
            redirect(U("Admin/Index/index"));exit();
        }
        if(IS_POST){
            $UserName = I('UserName');
            $Password = I('Password');
            $where['UserName'] = $UserName;
            $where['IsDel'] = array('neq','1');
            $user = M('User')->where($where)->find();
            if($user){
                if($user['Password'] === sp_password($Password,'',$UserName)){
                    $this->storeLogin($user);
                    $this->success('登录成功');
                }
            }
            $this->error('用户名或密码错误');
        }else{
            $this->display();
        }
    }

    public function test(){
        $this->display();
    }

}